package com.zzy.demo.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.zzy.demo.entity.FileInfo;

/**
 * @category Class description
 * @author heyingcheng
 * @email horay_hyc@qq.com
 * @date 2017/12/18 22:47
 */
@RestController
@RequestMapping("/file")
public class FileController {

	@PostMapping
	public FileInfo file(MultipartFile file) throws IOException {
		System.out.println(file.getName());
		System.out.println(file.getOriginalFilename());
		System.out.println(file.getSize());

		String dir = "D:\\uploadTest";
		File localFile = new File(dir, System.currentTimeMillis() + ".txt");
		file.transferTo(localFile);

		return new FileInfo(localFile.getAbsolutePath());
	}

	@GetMapping("{id:\\d+}")
	public void download(@PathVariable String id, HttpServletResponse response) {
		String dir = "D:\\uploadTest";
		File localFile = new File(dir, id + ".txt");
		try (InputStream inputStream = new FileInputStream(localFile); OutputStream outputStream = response.getOutputStream()) {
			response.setContentType("application/x-download");
			response.addHeader("Content-Disposition", "attachment;filename=test.txt");
			IOUtils.copy(inputStream, outputStream);
			outputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
